<!DOCTYPE html>
<html>
<head>
    <title>用户列表</title>
    <link rel="stylesheet" href="${request.contextPath}/resources/layui/css/layui.css">
</head>
<body>
<div style="margin-left: 10px;margin-top: 10px">
    <form class="layui-form layui-form-pane">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-inline" style="width: 150px">
                    <input type="text" class="layui-input" id="realname" placeholder="姓名" autocomplete="off">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">电话</label>
                <div class="layui-input-inline" style="width: 150px">
                    <input type="text" class="layui-input" id="phone" placeholder="电话" autocomplete="off">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-inline" style="width: 150px">
                    <select id="sex">
                        <option value="">性别</option>
                        <option value="1">男</option>
                        <option value="2">女</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-inline" style="width: 150px">
                    <select id="deleted">
                        <option value="">状态</option>
                        <option value="1">有效</option>
                        <option value="2">无效</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <button type="button" class="layui-btn" id="searchBtn">查询</button>
            </div>
        </div>
    </form>
    <hr>
    <table id="dataTable" lay-filter="dataTableFilter"></table>
</div>

<script type="text/html" id="editTpl">
    <form class="layui-form layui-form-pane" style="margin-top: 15px;margin-left: 15px">
        <div class="layui-form-item">
            <label class="layui-form-label">
                姓名
            </label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" name="realname" placeholder="姓名" lay-verify="required" lay-reqText="姓名不能为空" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">登录名</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" name="loginName" placeholder="登录名" lay-verify="required" lay-reqText="登录名不能为空" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" name="phone" placeholder="手机号" lay-verify="required|phone" lay-reqText="手机号不能为空" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-inline">
                <input type="radio" name="sex" value="1" checked title="男">
                <input type="radio" name="sex" value="2" title="女">
            </div>
        </div>
        <div class="layui-form-item layui-form-text" style="width: 300px">
            <label class="layui-form-label">地址</label>
            <div class="layui-input-block">
                <textarea class="layui-textarea" name="address"></textarea>
            </div>
        </div>
        <button id="subBtn" type="button" lay-filter="subBtnFilter" lay-submit style="display: none"></button>
    </form>
</script>

<script type="text/html" id="setRoleTpl">
    <form class="layui-form layui-form-pane" lay-filter="setRoleFormFilter" style="margin-top: 15px;margin-left: 15px">
        <div class="layui-form-item layui-form-text" style="width: 350px;">
            <label class="layui-form-label">
                角色
            </label>
            <div class="layui-input-inline" id="rolesContent">
            </div>
        </div>

        <button id="subBtn1" type="button" lay-filter="subBtnFilter" lay-submit style="display: none"></button>
    </form>


</script>
<script type="text/html" id="headerBtns">
    <div class="layui-btn-group">
        <button class="layui-btn layui-btn-sm" type="button" lay-event="add">
            <i class="layui-icon layui-icon-add-1"></i>添加
        </button>
    </div>
</script>

<script type="text/html" id="rowBtns">
    <div class="layui-btn-group">
        <button class="layui-btn layui-btn-sm" type="button" lay-event="reset">
            <i class="layui-icon layui-icon-refresh"></i>重置密码
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" type="button" lay-event="delete">
            <i class="layui-icon layui-icon-delete"></i>删除
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-warm" type="button" lay-event="setRole">
            <i class="layui-icon layui-icon-set"></i>设置角色
        </button>
    </div>
</script>


<script src="${request.contextPath}/resources/layui/layui.js"></script>
<script>
    layui.use(['form', 'table', 'jquery', 'layer'], function () {
        let cxt = "${request.contextPath}";
        let form = layui.form;
        let table = layui.table;
        let $ = layui.jquery;
        let layer = layui.layer;

        let tabOpt = {
            elem: "#dataTable",
            id: "dataTableId",
            url: cxt + "/sysuser/page.do",
            toolbar:"#headerBtns",
            cols: [[
                {field: "loginName", title: "登录名"},
                {field: "phone", title: "电话"},
                {field: "realname", title: "姓名"},
                {
                    field: "sex", title: "性别", templet: function (d) {
                        let sex = d.sex;
                        if (sex == 1) {
                            return "男";
                        } else if (sex == 2) {
                            return "女";
                        }
                    }
                },
                {field: "address", title: "地址"},
                {field: "createTime", title: "创建时间"},
                {title: "操作",toolbar:"#rowBtns",minWidth:250,fixed:"right"}
            ]],
            page: true,
            parseData: function (rs) {
                if (rs.code == 200) {
                    return {
                        code: rs.code,
                        msg: rs.msg,
                        count: rs.data.total,
                        data: rs.data.records
                    }
                }
            },
            response: {
                statusCode: 200
            }
        };
        //渲染数据表格
        let tabIns = table.render(tabOpt);
        //搜索
        $("#searchBtn").click(function (){
            let realName = $("#realname").val();
            let phone = $("#phone").val();
            let sex = $("#sex").val();
            let deleted = $("#deleted").val();
            tabIns.reload({
                where:{
                    realname:realName,
                    phone:phone,
                    sex:sex,
                    deleted:deleted
                }
            })
        });
        //头工具栏事件
        table.on("toolbar(dataTableFilter)",function (d){
            let event = d.event;
            if(event == "add"){
                //调用具体的add
                add();
            }
        })

        /**
         * 调用具体的add
         */
        function add(){
            let layerOpt = {
                title:"编辑",
                type:1,
                content:$("#editTpl").html(),
                area:['330px','560px'],
                btn:['确认','取消'],
                btnAlign:'c',
                anim:4,
                success:function (layero,index){
                    //渲染表单
                    form.render();
                    //设置表单提交监听事件
                    form.on("submit(subBtnFilter)",function (d){
                        let formData = d.field;
                        //进行ajax提交
                        $.post(cxt+"/sysuser/add.do",formData,function (rs){
                            layer.msg(rs.msg);
                            if(rs.code != 200){
                                return false;
                            }
                            //刷新表格
                            $("#searchBtn").click();
                            //关闭弹层
                            layer.close(index);
                        });

                        return false;//阻止默认提交行为
                    });
                },
                yes:function (index,layero){
                    $("#subBtn").click();
                }
            };
            layer.open(layerOpt);
        }


        //行工具栏事件
        table.on("tool(dataTableFilter)",function (d){
            let event = d.event;
            let rowData = d.data;
            if(event == "reset"){
                //调用具体的重置请求
                resetPassword(rowData);
            }else if(event == "delete"){
                del(rowData);
            }
            else if(event == "showImg"){
                showImg(rowData);
            }else if(event == "setRole"){
                setRole(rowData);
            }
        })

        /**
         * 重置密码
         * @param rowData  行数据
         */
        function resetPassword(rowData){
            layer.confirm("确定要重置密码吗?",function (index){
                $.get(cxt+"/sysuser/reset.do?id="+rowData.id,function (rs){
                    layer.msg(rs.msg);
                    layer.close(index);//关闭弹出层
                    $("#searchBtn").click();
                })
            })
        }

        /**
         * 删除用户
         * @param rowData  行数据
         */
        function del(rowData){
            layer.confirm("确定要删除吗?",function (index){
                $.get(cxt+"/sysuser/delete.do?id="+rowData.id,function (rs){
                    layer.msg(rs.msg);
                    layer.close(index);//关闭弹出层
                    $("#searchBtn").click();
                })
            })
        }

        /**
         * 显示用户头像
         * @param rowData
         */
        function showImg(rowData){
            let img = {
                "title": "用户头像", //相册标题
                "start": 0, //初始显示的图片序号，默认0
                "data": [   //相册包含的图片，数组格式
                    {
                        "alt": rowData.realname,
                        "src": cxt+"/"+rowData.img, //原图地址
                        "thumb": cxt+"/"+rowData.img,//缩略图地址
                    }
                ]
            };
            layer.photos({
                photos: img
                ,anim: 4 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
            });
            console.log(layer.photos);
        }

        /**
         * 设置角色
         * @param rowData
         */
        function setRole(rowData) {
            let layerOpt = {
                title:"编辑",
                type:1,
                content:$("#setRoleTpl").html(),
                area:['390px','560px'],
                btn:['确认','取消'],
                btnAlign:'c',
                anim:4,
                success:function (layero,index){
                    //查询所有的角色
                    //所有角色
                    let allRole = {};
                    $.ajax({
                        type:'get',
                        url:cxt+"/sysrole/roles.do",
                        async:false,//同步
                        success:function (rs){
                            if(rs.code != 200){
                                return false;
                            }
                            allRole = rs.data;
                        }
                    })
                    //查询当前用户所有的角色
                    let userRoles = {};
                    $.ajax({
                        type:'get',
                        url:cxt+"/sysrole/userRoles.do?userId="+rowData.id,
                        async:false,//同步
                        success:function (rs){
                            if(rs.code != 200){
                                return false;
                            }
                            userRoles = rs.data;
                        }
                    })
                    let userRoleId = new Array();//用户拥有的角色的数组
                    for(userRole of userRoles){
                        //将用户角色ID 放入数组
                        userRoleId.push(userRole.id);
                    }

                    //渲染复选框
                    // 角色复选框容器
                    let roles = $("#rolesContent");
                    for(r of allRole){
                        let input = "<input type='checkbox' value='"+r.id+"' title='"+r.name+"' />";
                        //如果包含 则增加 选中属性
                        if(userRoleId.includes(r.id)){
                            input =  "<input type='checkbox' value='"+r.id+"' title='"+r.name+"' checked />";
                        }
                        roles.append(input);
                    }
                    //渲染表单
                    form.render();
                    //设置表单提交监听事件
                    form.on("submit(subBtnFilter)",function (d){
                        //提交用户ID
                        let formData = {userId:rowData.id};//用户ID
                        //提交所有选中的角色ID
                        //遍历
                        /**
                         * 1. 拿到所有的选中的input
                         * 2. 获取选中的id的 value
                         */
                        let checkRole = new Array();//存储选中的角色ID的容器
                        //1. 拿到选中的input
                        let input = $("#rolesContent>input:checked");
                        //2. 获取选中的role
                        $.each(input,function (index,value) {
                            let roleId = $(value).val();
                            checkRole.push("roleId="+roleId);
                        })
                                       //roleId=1&role=2&role=3
                        let roleIds = checkRole.join("&"); //将所有的roleId 处理成拼接的形式
                        //进行ajax提交
                        $.post(cxt+"/sysuser/setRole.do?"+roleIds,formData,function (rs){
                            layer.msg(rs.msg);
                            if(rs.code != 200){
                                return false;
                            }
                            //刷新表格
                            $("#searchBtn").click();
                            //关闭弹层
                            layer.close(index);
                        });

                        return false;//阻止默认提交行为
                    });
                },
                yes:function (index,layero){
                    $("#subBtn").click();
                }
            };
            layer.open(layerOpt);


        }


    })
</script>
</body>
</html>
